package com.yzh.pleaSys.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.yzh.pleaSys.entity.DataDict.PWD_CODE;


/**
 * 发送邮件工具类
 */
public class EmailUtil {


    private static JavaMailSender mailSender;

    public EmailUtil(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Autowired
    private static StringRedisTemplate stringRedisTemplate;

    @Value("${spring.mail.username}")
//    @Value("${mail.fromMail.addr}")
    private static String fromEmail;

    public static String sendCodeByEmail(String to, String title, String content) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail); //发送人
        message.setTo(to);   //收件人
        message.setSubject(title);  //邮件名
        message.setText(content);   //邮件内容（验证码）
        mailSender.send(message);

        System.out.println("验证码发送成功");
        return "";
    }

    public static boolean sendCode(String email, String code) {
        try {
            sendCodeByEmail(email,
                    "改密验证",
                    email + "用户您好！您正在修改密码，验证码是" + code
                            + "，切勿将验证码泄露于他人，本条验证码有效期15分钟。"
            );
            stringRedisTemplate.opsForValue().set(PWD_CODE + ":" + email, code, 15, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
